<?php

namespace common\modules\user\controllers\backend;

use backend\components\AdminModule as Module;
use backend\components\RbacPhpManager;
use backend\widgets\AjaxModal;
use common\components\AdminController;
use common\modules\user\models\backend\PermissionForm;
use common\modules\user\models\backend\PermissionSearch;
use common\widgets\pages\AdminPage;
use Yii;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\Response;

/**
 * Permissions controller.
 *
 * @permissionDescription 许可管理
 */
class PermissionController extends AdminController
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = [];

        $behaviors['verbs'] = [
            'class'   => VerbFilter::className(),
            'actions' => [
                'index'        => ['get'],
                'create'       => ['get', 'post'],
                'update'       => ['get', 'put', 'post'],
                'delete'       => ['post', 'delete'],
                'batch-delete' => ['post', 'delete'],
            ],
        ];

        return $behaviors;
    }

    /**
     * @return string
     * @throws \yii\base\InvalidConfigException
     * @permissionDescription 刷新自动生成的许可列表
     */
    public function actionAjaxRefreshPermission()
    {
        $auth = Yii::$app->authManager;
        $appMetaDataComponent = Yii::$app->get('adminAuth');
        $appMetaDataComponent->refreshPermission($auth);
        $permissionCount = count($auth->getPermissions());
        $html = AjaxModal::createModal([
            'title'   => "提示",
            "content" => "已完成动态生成权限规则，数量：{$permissionCount}个 :)",
        ]);
        return $html;
    }

    /**
     * @return string
     * @permissionDescription 许可列表
     */
    public function actionIndex()
    {
        $searchModel = new PermissionSearch;
        $dataProvider = $searchModel->search(Yii::$app->request->get());

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        $page->addGridViewActionButton(
            AdminPage::genAjaxModalBtn('ajax-refresh-permission', "扫描并刷新权限节点")
        );

        return $page->render();
    }

    /**
     * Create permission page.
     *
     * @permissionDescription 新增许可
     */
    public function actionCreate()
    {
        $model = new PermissionForm(['scenario' => PermissionForm::SCENARIO_CREATE]);
        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            $model->loadAuthData();

            /** @var RbacPhpManager $auth */
            $auth = Yii::$app->authManager;
            $auth->setCustomEditMode();

            if ($model->validate())
            {
                if ($model->add())
                {
                    return $this->redirect(['update', 'name' => $model->name]);
                }
                else
                {
                    Yii::$app->session->setFlash('danger', Yii::t('backend/user', 'BACKEND_PERMISSIONS_FLASH_FAIL_ADMIN_CREATE'));
                }
            }
            elseif (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;

                return $model->getErrors();
            }
        }

        $page = $this->createFormViewPage(
            $model,
            PermissionForm::SCENARIO_CREATE,
            [
                'pageTitle' => Yii::t('backend/user', 'Create Permission'),
            ]
        );
        return $page->render();
    }

    /**
     * Update permission page.
     *
     * @param string $name Permission name
     *
     * @return mixed
     * @permissionDescription 更新许可
     */
    public function actionUpdate($name)
    {
        /** @var PermissionForm $model */
        $model = PermissionForm::findIdentity($name);
        $model->setScenario(PermissionForm::SCENARIO_UPDATE);

        if ($model->load(Yii::$app->request->post()))
        {
            $model->loadAuthData();

            /** @var RbacPhpManager $auth */
            $auth = Yii::$app->authManager;
            $auth->setCustomEditMode();

            if ($model->validate())
            {
                if ($model->update())
                {
                    return $this->refresh();
                }
                else
                {
                    Yii::$app->session->setFlash('danger', Module::t('user', 'BACKEND_PERMISSIONS_FLASH_FAIL_ADMIN_UPDATE'));
                }
            }
            elseif (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;

                return $model->getErrors();
            }
        }

        $page = $this->createFormViewPage(
            $model,
            PermissionForm::SCENARIO_UPDATE,
            [
                'pageTitle' => Yii::t('backend/user', 'Update Permission'),
            ]
        );
        return $page->render();
    }

    /**
     * Delete permission page.
     *
     * @param string $name Permission name
     *
     * @return mixed
     * @permissionDescription 删除许可
     */
    public function actionDelete($name)
    {
        /** @var RbacPhpManager $auth */
        $auth = Yii::$app->authManager;
        $auth->setCustomEditMode();

        $model = $this->findPermission($name);

        if ( ! Yii::$app->authManager->remove($model))
        {
            Yii::$app->session->setFlash('danger', Module::t('user', 'BACKEND_PERMISSIONS_FLASH_FAIL_ADMIN_DELETE'));
        }

        return $this->redirect(['index']);
    }

    /**
     * Find permission by name.
     *
     * @param string $name Permission name
     *
     * @return \yii\rbac\Permission Permission
     *
     * @throws HttpException 404 error if role not found
     */
    protected function findPermission($name)
    {
        if (($model = Yii::$app->authManager->getPermission($name)) !== null)
        {
            return $model;
        }
        else
        {
            throw new HttpException(404, Module::t('user', 'BACKEND_PERMISSIONS_NOT_FOUND'));
        }
    }
}
